<?php

namespace Home\Controller;

use Home\Controller\BaseController;

class OrderController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        if (!$this->user_id) {
            $this->error('请先登录');
        }
    }

    public function addOrder() {
        $user_id = $this->user_id;
        $prot_id = $this->getParam('prot_id', 0, 'int+', TRUE);
        $order_type = $this->getParam('order_type', 0, 'trim', TRUE);
        if (!in_array($order_type, boxModel())) {
            $this->error('选择的箱子型号不存在');
        }
        $shipment_time = $this->getParam('shipment_time', '', 'datetime', TRUE, '装箱时间错误');
        $cutoff_time = $this->getParam('cutoff_time', '', 'datetime', TRUE, '截关时间错误');
        $pick_no = $this->getParam('pick_no');
        $box_address_id = $this->getParam('box_address_id', 0, 'int+');
        $loadarea_id = $this->getParam('loadarea_id', 0, 'int+', TRUE, '请选择装箱区域');
        $shipment_address_id = $this->getParam('shipment_address_id', '', 'string', TRUE, '请选择装箱点');
        $driver_id = $this->getParam('driver_id', 0, 'int+');
        $message = $this->getParam('message');
        $dock_id = $this->getParam('dock_id', 0, 'int+');
        $weight_id = $this->getParam('weight_id', 0, 'int+');
        if (strtotime($shipment_time) >= strtotime($cutoff_time)) {
            $this->error("装箱时间不能比截关时间晚!");
        }

        $data['order_no'] = '1' . time() . mt_rand(1000, 9999);
        $data['company_user_id'] = $user_id;
        $data['company_id'] = M('CompanyUser')->where(['company_user_id'=>$user_id])->getField('company_id');
        $data['order_type'] = $order_type;
        $data['shipment_time'] = $shipment_time;
        $data['cutoff_time'] = $cutoff_time;
        $data['pick_no'] = $pick_no;
        $data['box_address_id'] = $box_address_id;
        $data['loadarea_id'] = $loadarea_id;
        $data['shipment_address_id'] = $shipment_address_id;
        $data['driver_id'] = $driver_id;
        $data['message'] = $message;
        $data['dock_id'] = $dock_id;
        $data['port_id'] = $prot_id;

        $data['weight_id'] = $weight_id;
        $data['dock_price'] = M('Dock')->where(['dock_id' => $dock_id])->getfield('dock_price');
        $data['weight_price'] = M('DockWeight')->where(['weight_id' => $weight_id])->getfield('weight_price');

        $shipment_address_id_arr = explode(',', $shipment_address_id);
        $ShipmentAddress = M('shipment_address');
        $portPriceInfo = M('port_price')->where(array('loadarea_id' => $loadarea_id, 'port_id' => $prot_id))->find();
        if ($portPriceInfo) {
            $arrPortPriceInfo = json_decode($portPriceInfo['freight_list'], TRUE);      //运价
            $arrSettlementList = json_decode($portPriceInfo['settlement_list'], TRUE);  //司机价
            $port_price = $arrPortPriceInfo[$order_type];
            $driver_price = $arrSettlementList[$order_type];
        } else {
            $port_price = 0;
            $driver_price = 0;
        }
        
        if($port_price == 0){
            $this->error('运价为0，无法下单。');
        }
        $data['order_price'] = empty($port_price) ? 0 : $port_price;
        $data['driver_price'] = empty($driver_price) ? 0 : $driver_price;
        
        D()->startTrans();
        $order_id = M('Order')->add($data);
        
        //添加装箱地址快照
        $LoadArea = M('load_area');
        $arrShipmentData = array();
        foreach ($shipment_address_id_arr as $val) {
            $shipmentAddressInfo = $ShipmentAddress->where(['shipment_address_id' => $val])->find();
            //关联装箱工
//            $boxman_id = $BoxmanModel->updateOrderBoxman($shipmentAddressInfo['shipment_linkman_phone'], $shipmentAddressInfo['shipment_linkman'], $order_id);
            $shipmentData['linkman_id'] = $shipmentAddressInfo['boxman_id'];            
            $shipmentData['order_id'] = $order_id;
            $shipmentData['address_type'] = 2;
            $shipmentData['address_id'] = $val;
            $shipmentData['json_content'] = json_encode($shipmentAddressInfo);
            $arrShipmentData[] = $shipmentData;
            
        }
        $shipmentRes = M('order_address')->addAll($arrShipmentData);
        
        //添加拿箱地址
        $boxAddressInfo = M('box_address')->field('box_address_id,user_id,box_linkman,box_linkman_phone,box_address_desc')->where(['box_address_id' => $box_address_id])->find();
        $boxData['order_id'] = $order_id;
        $boxData['address_type'] = 1;
        $boxData['address_id'] = $box_address_id;
        $boxData['json_content'] = json_encode($boxAddressInfo);
        $boxRes = M('order_address')->add($boxData);
        if ($order_id && $shipmentRes && $boxRes) {
            D()->commit();
            $this->returnList(['order_id'=>$order_id]);
        } else {
            D()->rollback();
            $this->error();
        }
    }

    //根据选择区域获取订单价格
    public function getOrderPrice() {
        $prot_id = $this->getParam('prot_id', 0, 'int+', TRUE);
        $order_type = $this->getParam('order_type', 0, 'trim', TRUE);
        if (!in_array($order_type, boxModel())) {
            $this->error('选择的箱子型号不存在');
        }
        $loadarea_id = $this->getParam('loadarea_id', 0, 'int+', TRUE, '请选择装箱区域');
        $shipment_address_id_arr = explode(',', $shipment_address_id);
        $portPriceInfo = M('port_price')->where(array('loadarea_id' => $loadarea_id, 'port_id' => $prot_id))->find();
        if ($portPriceInfo) {
            $arrPortPriceInfo = json_decode($portPriceInfo['freight_list'], TRUE);
            $port_price = $arrPortPriceInfo[$order_type];
        } else {
            $port_price = 0;
        }
        $data['order_price'] = $port_price;
        $this->returnList($data);
    }

    public function orderList() {
        $order_status = $this->getParam('order_status', -1, 'int+');
        $page = $this->getParam('page', 1, 'int+');
        if ($order_status != -1) {
            $where['order_status'] = $order_status;
        }
        $where['o.company_user_id'] = $this->user_id;
        $orderList = M()->table('ot_order o')->field('o.*,p.port_name,d.dock_name,d.dock_price,dr.driver_phone')
                ->join('LEFT JOIN ot_dock as d ON d.dock_id = o.dock_id')
                ->join('LEFT JOIN ot_port as p ON p.port_id = o.port_id')
                ->join('LEFT JOIN ot_driver as dr ON dr.driver_id = o.driver_id')
                ->where($where)
                ->order('o.order_id DESC')
                ->page($page)
                ->limit(10)
                ->select();
        
//        if ($orderList) {
//            $OrderAddress = M('order_address');
//            $LoadArea = M('load_area');
//            foreach ($orderList as &$val) {
//                $orderAddressInfo = $OrderAddress->where(array('order_id' => $val['order_id'], 'address_type' => 2))->order('order_address_id ASC')->select();
//                $val['shipment_address'] = array();
//                if(!empty($orderAddressInfo)){
//                    foreach($orderAddressInfo as $vv){
//                        $arr_shipment_address[] = json_decode($vv['json_content'], TRUE);
//                    }
//                }
//                $val['shipment_address'] = $arr_shipment_address;
//                $val['loadarea_address'] = $LoadArea->where(array('loadarea_id'=>$val['loadarea_id']))->find();
//            }
//            unset($val);
//        }
        
        if ($orderList) {
            $OrderAddress = M('order_address');
            $LoadArea = M('load_area');
            foreach ($orderList as &$val) {
                $orderAddressInfo = $OrderAddress->where(array('order_id' => $val['order_id'], 'address_type' => 2))->order('order_address_id ASC')->select();
                $val['shipment_address'] = array();
                $arr_shipment_address = array();
                if(!empty($orderAddressInfo)){
                    foreach($orderAddressInfo as $vv){
                        $arr_content = json_decode($vv['json_content'], TRUE);
                        $loadArea = $LoadArea->where(array('loadarea_id'=>$arr_content['loadarea_id']))->find();
                        $arr_content['province'] = $loadArea['province'];
                        $arr_content['city'] = $loadArea['city'];
                        $arr_content['loadarea_name'] = $loadArea['loadarea_name'];
                        $arr_shipment_address[] = $arr_content;
                    }
                }
                $val['shipment_address'] = $arr_shipment_address;
            }
            unset($val);
        }
        
        $this->returnList($orderList);
    }
    
    //企业订单统计数
    public function orderCountList(){
        $user_id = $this->user_id;
        $Order = M('Order');
        $return['wait_pay'] = $Order->where(array('order_status'=>0,'company_user_id'=>$user_id))->count();
        $return['allotting'] = $Order->where(array('order_status'=>10,'company_user_id'=>$user_id))->count();
        $return['allotted'] = $Order->where(array('order_status'=>20,'company_user_id'=>$user_id))->count();
        $return['under_way'] = $Order->where(array('order_status'=>30,'company_user_id'=>$user_id))->count();
        $return['second_wait_pay'] = $Order->where(array('order_status'=>40,'company_user_id'=>$user_id))->count();
        $this->returnList($return);
    }

    //订单支付
    public function payOrder() {
        $user_id = $this->user_id;
        $order_id = $this->getParam('order_id', 0, 'int+', TRUE);
        $orderInfo = M('order')->where(array('order_id' => $order_id))->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }

        if ($orderInfo['order_status'] != 0) {
            $this->error('该订单状态非待支付，所以不能支付');
        }
        $userInfo = M()->table('ot_company_user cu')->field('c.company_id,c.total_amount')
                ->join('ot_company as c USING(company_id)')
                ->where(array('cu.company_user_id' => $user_id))
                ->find();
        
        if (floatval($userInfo['total_amount']) < floatval($orderInfo['order_price'])) {
            $this->error('账户金额不足，请先充值');
        }

        $CompanyModel = new \Common\Model\CompanyModel();
        $res = $CompanyModel->changeWallet($userInfo['company_id'], 1, $orderInfo['order_price'], $order_id);
        if ($res) {
            M('Order')->where(array('order_id' => $order_id))->save(['order_status' => 10]);
            $this->success();
        } else {
            $this->error();
        }
    }

    //订单详情
    public function orderDetail() {
        $order_id = $this->getParam('order_id', 0, 'int+', TRUE);

        $where['o.order_id'] = $order_id;
        $orderInfo = M()->table('ot_order o')->field('o.*,p.port_name,d.dock_name,d.dock_price,dw.weight_desc,dr.driver_phone,dr.driver_face,dr.driver_name,dr.car_no,dr.driver_lon,dr.driver_lat,dr.lon_lat_address,y.yard_name,y.yard_price')
                ->join('LEFT JOIN ot_dock as d ON d.dock_id = o.dock_id')
                ->join('LEFT JOIN ot_port as p ON p.port_id = d.port_id')
                ->join('LEFT JOIN ot_dock_weight as dw ON dw.port_id = p.port_id')
                ->join('LEFT JOIN ot_driver as dr ON dr.driver_id = o.driver_id')
                ->join('LEFT JOIN ot_yard as y ON y.yard_id = o.yard_id')
                ->where($where)
                ->find();
        if ($orderInfo) {
            $OrderAddress = M('order_address');
            $LoadArea = M('load_area');
            $Boxman = M('boxman');
            
            $orderAddressList = $OrderAddress->where(array('order_id' => $orderInfo['order_id']))->order('order_address_id ASC')->select();
            if ($orderAddressList) {
                $orderInfo['box_address'] = array();
                $orderInfo['shipment_address'] = array();
                foreach ($orderAddressList as $val) {
                    if ($val['address_type'] == 1) {
                        $orderInfo['box_address'][] = json_decode($val['json_content'], TRUE);
                    }
                    
                    if ($val['address_type'] == 2) {
                        $arr_content = json_decode($val['json_content'], TRUE);
                        $loadArea = $LoadArea->where(array('loadarea_id'=>$arr_content['loadarea_id']))->find();
                        $arr_content['province'] = $loadArea['province'];
                        $arr_content['city'] = $loadArea['city'];
                        $arr_content['loadarea_name'] = $loadArea['loadarea_name'];
                        //装箱工
                        $boxmanInfo = $Boxman->where(['boxman_id'=>$arr_content['boxman_id']])->find();
                        $arr_content['boxman_name'] = $boxmanInfo['boxman_name'];
                        $arr_content['boxman_phone'] = $boxmanInfo['boxman_phone'];
                        $arr_shipment_address[] = $arr_content;
                    }
                }
                $orderInfo['shipment_address'] = $arr_shipment_address;
            }
            //物流信息
            $orderInfo['logistics'] = M('order_logistics')->where(['order_id' => $order_id])->order('order_logistics_id DESC')->select();
            
            //装箱图列表
            if(!empty($orderInfo['box_img'])){
                $arr_box_img = json_decode($orderInfo['box_img'], TRUE);
                foreach($arr_box_img as &$vv){
                    $vv = C('SITE_URL').$vv;
                }
                unset($vv);
            }
            $orderInfo['box_img'] = $arr_box_img;
            
            //其他费用图片
            if(!empty($orderInfo['other_price_img'])){
                $arr_other_price_img = json_decode($orderInfo['other_price_img'], TRUE);
                foreach($arr_other_price_img as &$vv){
                    $vv = C('SITE_URL').$vv;
                }
                unset($vv);
            }
            $orderInfo['other_price_img'] = $arr_other_price_img;
            
            $orderInfo['other_price_total'] = floatval($orderInfo['dock_price']+$orderInfo['weight_price']+$orderInfo['yard_price']+$orderInfo['other_price']+$orderInfo['admin_price']);
        }
        $this->returnList($orderInfo);
    }

    public function cancelOrder() {
        $user_id = $this->user_id;
        $order_id = $this->getParam('order_id', 0, 'int+', TRUE);
        $where['order_id'] = $order_id;
        $where['company_user_id'] = $user_id;
        $orderInfo = M('order')->where($where)->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }

        if ($orderInfo['order_status'] != 10) {
            $this->error('该订单无法取消');
        }
        $userInfo = M()->table('ot_company_user cu')->field('c.company_id,c.total_amount')
                ->join('ot_company as c USING(company_id)')
                ->where(array('cu.company_user_id' => $user_id))
                ->find();

        $CompanyModel = new \Common\Model\CompanyModel();
        $res = $CompanyModel->changeWallet($userInfo['company_id'], 6, $orderInfo['order_price'], $order_id);
        if ($res) {
            M('Order')->where(array('order_id' => $order_id))->save(['order_status' => 60]);
            $this->success();
        } else {
            $this->error();
        }
    }
    
    //支付其他费用
    public function payOrderOtherPrice() {
        $user_id = $this->user_id;
        $order_id = $this->getParam('order_id', 0, 'int+', TRUE);
        $orderInfo = M('order')->where(array('order_id' => $order_id))->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }

        if ($orderInfo['order_status'] != 40 || $orderInfo['is_other_pay'] != 0) {
            $this->error('该订单状态非待支付，所以不能支付');
        }
        
        //待支付金额总和：
        $otherPirceTotal = floatval($orderInfo['dock_price']+$orderInfo['weight_price']+$orderInfo['yard_price']+$orderInfo['other_price']+$orderInfo['admin_price']);
        $userInfo = M()->table('ot_company_user cu')->field('c.company_id,c.total_amount')
                ->join('ot_company as c USING(company_id)')
                ->where(array('cu.company_user_id' => $user_id))
                ->find();
        
        if (floatval($userInfo['total_amount']) < floatval($otherPirceTotal)) {
            $this->error('账户金额不足，请先充值');
        }

        $CompanyModel = new \Common\Model\CompanyModel();
        $res = $CompanyModel->changeWallet($userInfo['company_id'], 2, $otherPirceTotal, $order_id);
        if ($res) {
            M('Order')->where(array('order_id' => $order_id))->save(['order_status' => 50]);
            //转钱到司机
            $DriverModel = new \Common\Model\DriverModel();
            $res = $DriverModel->driverChangeWallet($orderInfo['driver_id'], 5, $orderInfo['driver_price'], $order_id);
            $this->success();
        } else {
            $this->error();
        }
    }

}
